<template>
  <el-card class="user-profile-card">
    <div slot="header">
      <h2>{{ user.username }} 的个人主页</h2>
    </div>

    <div class="user-info">
      <div class="avatar">
        <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar">
        </el-avatar>
      </div>
      <div class="info-details">
        <div class="info-item">
          <strong>用户名：</strong> {{ userInfo.username }}
        </div>
        <div class="info-item">
          <strong>邮箱：</strong> {{ userInfo.email }}
        </div>
        <div class="info-item">
          <strong>注册时间：</strong> {{ userInfo.created_at }}
        </div>
        <div class="info-item">
          <strong>角色：</strong>
          <el-tag :type="userInfo.role === 'admin' ? 'danger' : 'success'">
            {{ userInfo.role === "admin" ? "管理员" : "普通用户" }}
          </el-tag>
        </div>
        <div class="info-item" v-if="userInfo.bio">
          <strong>个人简介：</strong> {{ userInfo.bio }}
        </div>
        <div class="action-buttons" v-if="isCurrentUser">
          <el-button
            @click="$router.push(`/user/${userInfo.id}/edit?type=profile`)"
            icon="el-icon-edit"
            >编辑资料
          </el-button>
          <el-button
            type="primary"
            @click="$router.push('/profile/change-password')"
            icon="el-icon-key"
            >修改密码
          </el-button>
        </div>
      </div>
    </div>

    <div class="user-blogs">
      <h3>{{ user.username }} 的博客 ({{ blogCount }})</h3>
      <div class="blog-list">
        <el-card class="blog-item" v-for="blog in blogs" :key="blog.id">
          <div class="blog-title">
            <router-link :to="`/blog/${blog.id}`">
              {{ blog.title }}
            </router-link>
          </div>
          <div class="blog-meta">
            <span>发布时间: {{ blog.created_at }}</span>
          </div>
          <div class="blog-excerpt">
            {{
              blog.content.length > 100
                ? blog.content.substring(0, 100) + "..."
                : blog.content
            }}
          </div>
          <div class="blog-actions">
            <router-link :to="`/blog/${blog.id}`" class="read-more"
              >阅读全文</router-link
            >
          </div>
        </el-card>
      </div>

      <div v-if="blogs.length === 0" class="no-data">暂无博客</div>

      <el-pagination
        class="pagination"
        layout="prev, pager, next"
        :total="blogCount"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        // user: {},
        userInfo: {},
        blogs: [],
        blogCount: 0,
        pageSize: 5,
        currentPage: 1,
        userId: null,
        isCurrentUser: false,
        defaultAvatar: "https://picsum.photos/200/200?random=1",
      };
    },
    computed: {
      user() {
        return this.$store.getters.user;
      },
    },
    created() {
      // console.log("UserProfile created,", this.$route);
      const targetUserId = this.$route.params.id;
      // const currentUser = JSON.parse(localStorage.getItem('user') || '{}')
      const currentUser = this.user;

      // 检查是否是当前登录用户
      this.isCurrentUser =
        currentUser.userId && currentUser.userId.toString() === targetUserId;

      this.loadUserInfo(targetUserId);
      this.loadUserBlogs(targetUserId);
    },
    methods: {
      async loadUserInfo(userId) {
        try {
          const user = await this.$axios.get(`/user/${userId}`);
          this.userInfo = user.data;
          this.userInfo.avatar = "";
        } catch (error) {
          this.$message.error("加载用户信息失败");
          console.error(error);
        }
      },
      async loadUserBlogs(userId) {
        try {
          const result = await this.$axios.get(
            `/user/${userId}/blogs?page=${this.currentPage}&pageSize=${this.pageSize}`
          );
          let resultData = result.data;
          this.blogs = resultData.data;
          this.blogCount = resultData.total;
        } catch (error) {
          this.$message.error("加载用户博客失败");
          console.error(error);
        }
      },
      handlePageChange(page) {
        this.currentPage = page;
        this.loadUserBlogs(this.$route.params.id);
      },
    },
  };
</script>

<style scoped>
  .user-profile-card {
    max-width: 1000px;
    margin: 20px auto;
  }

  .user-info {
    display: flex;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
  }

  .avatar {
    margin-right: 30px;
  }

  .info-details {
    flex: 1;
  }

  .info-item {
    margin-bottom: 10px;
    line-height: 1.6;
  }

  .action-buttons {
    margin-top: 20px;
  }

  .action-buttons button {
    margin-right: 10px;
  }

  .user-blogs {
    margin-top: 30px;
  }

  .user-blogs h3 {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .blog-item {
    margin-bottom: 15px;
  }

  .blog-title {
    font-size: 16px;
    margin-bottom: 5px;
  }
  .dark .blog-title a {
    color: #d1d1d1;
  }

  .blog-title a {
    color: #333;
    text-decoration: none;
  }

  .blog-title a:hover {
    color: #409eff;
  }

  .blog-meta {
    color: #666;
    font-size: 12px;
    margin-bottom: 5px;
  }

  .blog-excerpt {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 10px;
  }

  .read-more {
    color: #409eff;
    text-decoration: none;
    font-size: 14px;
  }

  .no-data {
    text-align: center;
    padding: 30px 0;
    color: #999;
  }

  .pagination {
    margin-top: 20px;
    text-align: center;
  }
</style>
